﻿using System.Web.UI;

namespace PmfWeb.Core.Forms
{
    /// <summary>
    /// 自定义页面状态持久器
    /// </summary>
    public class CompressPageStatePersister:PageStatePersister
    {
        #region 属性
        //页面状态保存在页面中的字段名
        private const string STATEKEY = "____VIEWSTATE";
        ///<summary>
        /// 构造器
        ///</summary>
        ///<param name="page">当前页对象</param>
        public CompressPageStatePersister(Page page) : base(page) { } 
        #endregion

        #region 加载
        /// <summary>
        /// 重写页面加载事件
        /// </summary>
        public override void Load()
        {
            //取得保存到客户端的状态内容
            string postbackState = Page.Request.Form[STATEKEY];
            if (!string.IsNullOrEmpty(postbackState))
            {
                //解压,反序列化状态,
                //ASP.NET2.0中的页面状态包括视图状态和控件状态两部分
                Pair statePair = (Pair)GZipCompress.Decompress(postbackState);
                if (!Page.EnableViewState)
                {
                    ViewState = null;
                }
                else
                {
                    ViewState = statePair.First;
                }
                ControlState = statePair.Second;
            }
        } 
        #endregion

        #region 保存
        /// <summary>
        /// 重写保存页面状态方法
        /// </summary>
        public override void Save()
        {
            if (!Page.EnableViewState)
            {
                ViewState = null;
            }
            if (ViewState != null || ControlState != null)
            {
                string stateString;
                Pair statePair = new Pair(ViewState, ControlState);
                //序列化并压缩状态
                stateString = GZipCompress.Compress(statePair);
                Page.ClientScript.RegisterHiddenField(STATEKEY, stateString);
                int temp=stateString.Length;
            }
        } 
        #endregion
    }
}